package cn.ejiakanghu.logistics.task;

import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.core.rabbitmq.DirectExchangeProducer;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.lock_rfid.LockRfidUtil;
import org.linlinjava.litemall.core.lock_rfid.UnLockCabinetGoodsVo;
import org.linlinjava.litemall.core.lock_rfid.UnLockGoodsVo;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.dao.AgedmallHospitalSendSelfLocationMapper;
import org.linlinjava.litemall.db.dao.AgedmallServiceOrderMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallGoodsProductService;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderGoodsConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.ServiceOrderConstant;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wj
 * @date 2021/12/31 10:43
 */
public class OrderSelfTask extends Task {
    private final Log logger = LogFactory.getLog(OrderSelfTask.class);
    /**
     * 子订单id
     */
    private int orderId = -1;

    public OrderSelfTask(Integer orderId, long delayInMilliseconds){
        super("OrderSelfTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderSelfTask(Integer orderId){
        super("OrderSelfTask-" + orderId, 24 * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未自提---" + this.orderId);

        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        DirectExchangeProducer directExchangeProducer = BeanUtil.getBean(DirectExchangeProducer.class);
        LockRfidUtil lockRfidUtil = BeanUtil.getBean(LockRfidUtil.class);
        AgedmallServiceOrderMapper agedmallServiceOrderMapper = BeanUtil.getBean(AgedmallServiceOrderMapper.class);
        LitemallOrderGoodsService orderGoodsService = BeanUtil.getBean(LitemallOrderGoodsService.class);
        LitemallGoodsProductService productService = BeanUtil.getBean(LitemallGoodsProductService.class);
        AgedmallHospitalSendSelfLocationMapper agedmallHospitalSendSelfLocationMapper = BeanUtil.getBean(AgedmallHospitalSendSelfLocationMapper.class);

        LitemallOrderItem orderItemNow = orderService.findItemById(this.orderId);
        if(orderItemNow == null){
            return;
        }
        if(!OrderUtil.STATUS_SHIP_SELF.equals(orderItemNow.getOrderStatus())){
            return;
        }


        LitemallOrder order = orderService.findBySn(orderItemNow.getUserId(), orderItemNow.getOrderCode());
        order.setOrderStatus(OrderUtil.STATUS_CANCEL);
        order.setCancelReason("定时任务自提超时自动取消订单");
        order.setUpdateTime(LocalDateTime.now());
        orderService.update(order);

        // 更新服务订单
        AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
        serviceOrderExample.createCriteria().andDeletedEqualTo(false)
                .andOrderIdEqualTo(order.getId().longValue());
        AgedmallServiceOrder serviceOrder = new AgedmallServiceOrder();
        serviceOrder.setStat(ServiceOrderConstant.STATUS_CANCEL);
        agedmallServiceOrderMapper.updateByExampleSelective(serviceOrder, serviceOrderExample);

        List<LitemallOrderItem> orderItemList = orderService.getOrderItemListByBigOrderCode(orderItemNow.getUserId(), orderItemNow.getOrderCode());
        for (LitemallOrderItem orderItem : orderItemList) {
            // 更新子订单状态
            orderItem.setOrderStatus(OrderUtil.STATUS_CANCEL);
            orderService.updateItem(orderItem);
            String childOrderCode = orderItem.getChildOrderCode();
            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.getOrderGoodsListByChildOrderCode(childOrderCode);
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                // 还原库存数量 服务没有库存概念
                if (!OrderGoodsConstant.TYPE_EXTEND.equals(orderGoods.getType())) {
                    Integer productId = orderGoods.getProductId();
                    Short number = orderGoods.getNumber();
                    productService.addStock(productId, number);
                }
                if (StringUtils.isNotEmpty(orderGoods.getRfid())) {
                    List<String> rfidList = Arrays.asList(orderGoods.getRfid().split(","));
                    // 取消rfid锁定
                    if (InventoryUtil.STOCK_SOFTCHAIN.equals(orderGoods.getStockType())) {
                        UnLockGoodsVo unLockGoodsVo = new UnLockGoodsVo();
                        unLockGoodsVo.setRfid(rfidList);
                        int type=0;
                        //        如果为到院自提
                        AgedmallHospitalSendSelfLocation selfLocation = null;
                        if(orderGoods.getHospitalSelfLocationId()!=null){
                            selfLocation = agedmallHospitalSendSelfLocationMapper.selectByPrimaryKey(orderGoods.getHospitalSelfLocationId());
                        }
                        if(ObjectUtil.isNotNull(selfLocation)&&selfLocation.getInventoryFlag()==0){
                            type=2;
                        }
                        unLockGoodsVo.setType(type);
                        lockRfidUtil.unlockGoods(unLockGoodsVo);
                    }
                    if (InventoryUtil.STOCK_CABINET.equals(orderGoods.getStockType())) {
                        UnLockCabinetGoodsVo unLockCabinetGoodsVo = new UnLockCabinetGoodsVo();
                        unLockCabinetGoodsVo.setRfid(rfidList);
                        lockRfidUtil.unlockCabinetGoods(unLockCabinetGoodsVo);
                    }
                }
            }
        }



        Map<String, Object> refundData = new HashMap<>();
        refundData.put("refundMoney", orderItemNow.getActualPrice());
        refundData.put("bigOrderCode", orderItemNow.getOrderCode());
        refundData.put("childOrderCode", orderItemNow.getChildOrderCode());
        directExchangeProducer.send(JacksonUtil.toJson(refundData), DirectExchangeRabbitMQConfig.QUEUE_WX_REFUND);
        logger.info("系统结束处理延时任务---订单超时未自提---" + this.orderId);
    }
}
